package com.atguigu.day05;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;

public class Flink08_WaterMark_Customer {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

//        env.getConfig().setAutoWatermarkInterval(1000);

        //2.获取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.为了方便提取数据，将String类型的数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //TODO 4.指定WaterMark（自定义），并分配事件时间
        map.assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forGenerator(new WatermarkGeneratorSupplier<WaterSensor>() {
            @Override
            public WatermarkGenerator<WaterSensor> createWatermarkGenerator(Context context) {
                return new MyWaterMark(Duration.ofSeconds(3));
            }
        })
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs() * 1000;
                    }
                }))
                .keyBy("id")
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .sum("vc")
                .print();

        env.execute();
    }

    //自定义生成WaterMark
    public static class MyWaterMark implements WatermarkGenerator<WaterSensor>{

        private long maxTimestamp;
        private long outOfOrdernessMillis;

        public MyWaterMark(Duration maxOutOfOrderness){
            outOfOrdernessMillis = maxOutOfOrderness.toMillis();
            maxTimestamp = Long.MIN_VALUE + outOfOrdernessMillis + 1;
        }


        //断点式生成WaterMark
        @Override
        public void onEvent(WaterSensor event, long eventTimestamp, WatermarkOutput output) {
            maxTimestamp = Math.max(maxTimestamp, eventTimestamp);
//            System.out.println("WaterMark:"+(maxTimestamp-outOfOrdernessMillis-1));
//            output.emitWatermark(new Watermark(maxTimestamp - outOfOrdernessMillis - 1));
        }

        //周期性生成WaterMark
        @Override
        public void onPeriodicEmit(WatermarkOutput output) {
//            System.out.println("WaterMark:"+(maxTimestamp-outOfOrdernessMillis-1));
            System.out.println("WaterMark:");
            output.emitWatermark(new Watermark(maxTimestamp - outOfOrdernessMillis - 1));
        }
    }
}
